package com.action.proceso5;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger; 

import com.bean.proceso5.Proveedor;
import com.conexion.DbConnection;

public class ProveedorAction {

	private final String TABLA = "proveedor";

	public ArrayList<Proveedor> listar() {

		Connection conn = null;
		PreparedStatement pstm = null;

		ArrayList<Proveedor> lista = new ArrayList<Proveedor>();
		try {
			conn = DbConnection.getConnection();

			String sql = "Select * FROM " + TABLA;
			pstm = conn.prepareStatement(sql);

			ResultSet rs = pstm.executeQuery();

			while (rs.next()) {
				lista.add(new Proveedor(rs.getString(1), rs.getString(2), rs
						.getString(3), rs.getString(4), rs.getString(5), rs
						.getString(6)));
			}

		} catch (SQLException e) {
			Logger.getLogger(ProveedorAction.class.getName()).log(Level.SEVERE,
					null, e);
		} finally {
			try {
				if (pstm != null)
					pstm.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return lista;
	}

	public Proveedor buscarRUC(String ruc) {

		Connection conn = null;
		PreparedStatement pstm = null;
		Proveedor p = null;

		try {

			conn = DbConnection.getConnection();

			String sql = "Select * FROM " + TABLA + " where ruc=?";
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, ruc);

			ResultSet rs = pstm.executeQuery();

			if (rs.next())
				p = new Proveedor(rs.getString(1), rs.getString(2),
						rs.getString(3), rs.getString(4), rs.getString(5),
						rs.getString(6));

		} catch (SQLException e) {
			Logger.getLogger(ProveedorAction.class.getName()).log(Level.SEVERE,
					null, e);
		} finally {
			try {
				if (pstm != null)
					pstm.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return p;
	}
	
	public Proveedor buscarRS(String razonSocial) {

		Connection conn = null;
		PreparedStatement pstm = null;
		Proveedor p = null;

		try {

			conn = DbConnection.getConnection();

			String sql = "Select * FROM " + TABLA + " where razonsocial=?";
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, razonSocial);

			ResultSet rs = pstm.executeQuery();

			if (rs.next())
				p = new Proveedor(rs.getString(1), rs.getString(2),
						rs.getString(3), rs.getString(4), rs.getString(5),
						rs.getString(6));

		} catch (SQLException e) {
			Logger.getLogger(ProveedorAction.class.getName()).log(Level.SEVERE,
					null, e);
		} finally {
			try {
				if (pstm != null)
					pstm.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return p;
	}

}
